//    Copyright (C) Kherty.  All rights reserved.
using System.Windows.Media;
using OpenLS.Core.Serialization;
using System.Windows.Media.Imaging;
using OpenLS.Drawing.Serialization;

namespace OpenLS.Drawing
{
    public class BlipFillProperties : FillProperties
    {
        public BlipFillProperties()
        {
            
        }

        public BlipFillProperties(BitmapSource source)
        {
            blip = new Blip {Source = source};
        }
        private Blip blip;
        private int? dpi;
        private FillModeProperties fillModeProperties;
        private bool rotWithShape = true; //\\not sure?

        private RelativeRectangle srcRect;

        public Blip Blip
        {
            get { return blip; }
            set { blip = value; }
        }

        public RelativeRectangle SourceRectangle
        {
            get { return srcRect; }
            set { srcRect = value; }
        }

        public FillModeProperties FillModeProperties
        {
            get { return fillModeProperties; }
            set { fillModeProperties = value; }
        }

        public int? Dpi
        {
            get { return dpi; }
            set { dpi = value; }
        }

        public bool RotateWithShape
        {
            get { return rotWithShape; }
            set { rotWithShape = value; }
        }

        internal override void ReadXmlCore(ReadContext context)
        {
            using (var c = context.ReadAndSwitch("blipFill", DrawingConstants.DrawingNamespaceUri, false))
            {
                RotateWithShape = c.GetOptionalBoolean("rotWithShape", true);
                Dpi = c.GetOptionalInteger("dpi");
                Blip = c.ReadOptionalElement<Blip>("blip");
                SourceRectangle = c.ReadOptionalElementAs<RelativeRectangle>("srcRect");
                FillModeProperties = FillModeProperties.ReadOptionalFillModeProperties(c);
            }
        }

        internal override void WriteXmlCore(WriteContext context)
        {
            using (WriteContext c = context.WriteAndSwitch("blipFill", DrawingConstants.DrawingNamespace))
            {
                c.SetOptionalDouble("dpi", Dpi);
                c.SetOptionalBoolean("rotWithShape", rotWithShape, true);
                c.WriteOptionalElement(Blip);
                c.WriteOptionalElementAs(SourceRectangle, "srcRect");
                c.WriteOptionalElement(FillModeProperties);
            }
        }


        internal override Brush ToBrush(ColorScheme colorScheme)
        {
            ImageBrush result = new ImageBrush(Blip.Source);
            if (FillModeProperties != null)
                FillModeProperties.Apply(result);
            return result;
        }
    }
}